﻿using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Daemon.Data.Substructure.Const;
using Daemon.Model;
using Newtonsoft.Json.Linq;

namespace Daemon.Data.Infrastructure.Auth
{
	public static class AuthInfoHelper
	{
		public static JObject BulidAuthTree(BaseAuthUser user)
		{
			JObject authTree = new JObject();
			JObject securedItems = new JObject();
			JObject securedGroupedItems = new JObject();
			authTree.Add("securedItems", securedItems);
			authTree.Add("securedGroupedItems", securedGroupedItems);
			authTree.Add("username", user.UserName);
			authTree.Add("userId", user.Id);
			return authTree;
		}

		public static bool IsAdministrator(BaseAuthUser user)
		{
			return user.IsAdmin || user.RoleIds.Any(r => r == SystemConst.ADMINISTRATOR_ROLE_ID);
		}

		public static string CompressSecuredItemName(string input)
		{
			return Regex.Replace(input, "[^A-Za-z0-9]", string.Empty);
		}

		public static string NormalizeSecuredItem(string securedItemName)
		{
			string output = CompressSecuredItemName(securedItemName);
			return char.ToLowerInvariant(output[0]) + output.Substring(1);
		}

		public static string NormalizeSecureRightName(string secureRightName)
		{
			string output = CompressSecuredItemName(secureRightName);
			return char.ToLowerInvariant(output[0]) + output.Substring(1);
		}

		public static string NormalizeSecuredItemGroupName(string name)
		{
			string output = CompressSecuredItemName(name);

			return char.ToLowerInvariant(output[0]) + output.Substring(1);
		}

		public static void UpdateSecuredItemsRelated(JObject securedItems, JObject securedGroupedItems,  IEnumerable<RoleSecuredItem> roleSecuredItems)
		{
			foreach (RoleSecuredItem roleSecuredItemEntity in roleSecuredItems)
			{
				string compressedSecuredItemName = NormalizeSecuredItem(roleSecuredItemEntity.SecuredItem.Name);
				var groupName = roleSecuredItemEntity.SecuredItem.SecuredItemGroup?.Name ?? string.Empty;
				string compressedSecurityRightName = NormalizeSecureRightName(roleSecuredItemEntity.SecurityRight.Name);

				// #region compose grouped secured item
				// TODO: Should include secured item group for SAML and AD user in the further. SF-14221
				groupName = NormalizeSecuredItemGroupName(groupName);
				JToken groupedItem;
				if (!securedGroupedItems.TryGetValue(groupName, out groupedItem))
				{
					groupedItem = new JObject();
					securedGroupedItems.Add(groupName, (JObject)groupedItem);
				}

				if (groupedItem[compressedSecuredItemName] == null)
				{
					groupedItem[compressedSecuredItemName] = new JArray();
				}

				JArray groupSecuredItem = (JArray)groupedItem[compressedSecuredItemName];
				JToken matchOfGroupSecuredItem = groupSecuredItem.FirstOrDefault(j => j.ToString().Equals(compressedSecurityRightName));
				if (matchOfGroupSecuredItem == null)
				{
					groupSecuredItem.Add(compressedSecurityRightName);
				}

				// #endregion
			}
		}
	}
}
